<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="产品ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否有货" prop="hasStock">
        <el-select
          v-model="queryParams.hasStock"
          placeholder="请选择是否有货"
          clearable
        >
          <el-option
            v-for="dict in product_has_stock"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['jewelry:product:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jewelry:product:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jewelry:product:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['jewelry:product:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品ID" align="center" prop="id" />
      <el-table-column label="pId" align="center" prop="pid" />
      <el-table-column label="产品名称" align="center" prop="name" />
      <el-table-column label="品牌" align="center" prop="brandName" >
      </el-table-column>

      <el-table-column label="首图" align="center" prop="mainImage" width="80">
        <template #default="scope">
          <image-preview :src="scope.row.mainImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="图集" align="center" prop="atlas" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.atlas" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="是否有货" align="center" prop="hasStock">
        <template #default="scope">
          <dict-tag :options="product_has_stock" :value="scope.row.hasStock" />
        </template>
      </el-table-column>

      <el-table-column label="原价(单位：元)" align="center">
        <template #default="scope">
          <!-- 直接显示转换后的价格（分→元） -->
          {{ scope.row.price ? (scope.row.price / 100).toFixed(2) : "0.00" }}
        </template>
      </el-table-column>
      <el-table-column label="折扣价(单位：元)" align="center">
        <template #default="scope">
          {{
            scope.row.newPrice ? (scope.row.newPrice / 100).toFixed(2) : "0.00"
          }}
        </template>
      </el-table-column>

      <el-table-column label="折扣" align="center" prop="offPercent" />
      <!-- <el-table-column label="商品描述" align="center" prop="summary" />
        <el-table-column label="详细描述" align="center" prop="description" /> -->
      <el-table-column label="其他信息" align="center" prop="additionalInfo" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-space direction="vertical" :size="8" align="start">
            <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['jewelry:product:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['jewelry:product:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            icon="DocumentCopy"
            @click="handCopy(scope.row)"
            v-if="scope.row.pid === 0"
            >复制</el-button>
          </el-space>
          
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1500px" append-to-body>
      <el-form
        ref="productRef"
        :model="form"
        :rules="rules"
        label-width="160px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入产品名称" 
              :maxlength="50"
              show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有货" prop="hasStock">
              <el-radio-group v-model="form.hasStock">
                <el-radio
                  v-for="dict in product_has_stock"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价(单位：元)" prop="price">
            <el-input v-model="form.price" placeholder="请输入原价(单位：分)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣价(单位：元）" prop="newPrice">
              <el-input
                v-model="form.newPrice"
                placeholder="请输入折扣价(单位：分）"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="折扣" prop="offPercent">
            <el-input v-model="form.offPercent" placeholder="请输入折扣" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品描述" prop="summary">
              <el-input v-model="form.summary" placeholder="请输入商品描述" 
              :maxlength="500"
              show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="详细描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请输入内容"
                :maxlength="1000"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他信息" prop="additionalInfo">
              <el-input
                v-model="form.additionalInfo"
                type="textarea"
                placeholder="请输入内容"
                :maxlength="1000"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 15px;">
          <el-col :span="12">
            <el-form-item label="首图" prop="atlas">
              <image-upload v-model="form.mainImage" 
                :limit="1"
                />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图集" prop="atlas">
              <image-upload 
                v-model="form.atlas" 
                @on-success="handleAtlasUploadSuccess"
                />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 15px;">
          <el-col :span="12">
            <!-- 仅当form.pid存在且不等于0时显示（排除null和0的情况） -->
            <el-form-item label="请选择首图" prop="" v-if="form.pid && form.pid !== 0">
              <el-select 
               v-model="form.mainImage"
               style="width: 240px"
              >
                <el-option
                  v-for="(url, index) in (form.atlas || '').split(',')"
                  :key="index"
                  :label="`图片 ${index + 1}`"
                  :value="url"
                >
                  <img :src="`http://zbadminapi.kfcit.com//${url}`" style="width: 30px; height: 30px; object-fit: cover; margin-right: 5px; display: inline-block;">
                </el-option>
                <template #tag>
                  <!-- 插槽首图图片预览 -->
                  <!-- <img :src="`http://zbadminapi.kfcit.com//${form.mainImage}`" style="width: 30px; height: 30px; object-fit: cover; margin-right: 5px; display: inline-block;"> -->
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 15px;">
          <el-col :span="12">
            <el-form-item label="分类" prop="">
              <el-select
                v-model="categoriesSelected"
                placeholder="请选择分类"
                style="width: 240px"
                @change="handCategoryChange"
              >
                <el-option
                  v-for="item in categoriesOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="">
              <el-select
                v-model="tagsSelected"
                multiple
                placeholder="请选择标签"
                style="width: 240px"
                @change="$forceUpdate()"
              >
                <el-option
                  v-for="item in tagsOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20"  v-if="showSizeSection">
          <el-col :span="10">
            <!-- 输入尺码 -->
            <el-form-item label="尺码">
              <el-input 
                v-model="braceletSize"  
                placeholder="请输入尺码"  
                clearable 
                style="width: 240px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row :gutter="20" >
          <el-col :span="12" >
            <el-form-item label="分区" prop="">
              <el-select
                v-model="prodPartitionSelected"
                multiple
                placeholder="请选择分区"
                style="width: 240px"
              >
                <el-option
                  v-for="item in prodPartitionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="">
              <el-select
                v-model="form.brandId"
                clearable
                placeholder="请选择品牌"
              >
                <el-option
                  v-for="item in brandOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import {  listProduct,  getProduct,  delProduct,  addProduct,  updateProduct, listSelectRels, copyProduct } from "@/api/jewelry/product";
import { listCategoryAll } from "@/api/jewelry/category.js"
import { listTagAll } from "@/api/jewelry/tag.js"
import { listProdPartitionAll } from "@/api/jewelry/prodpartition.js";
import { listBrandAll } from "@/api/jewelry/brand.js"
import { getBraceletByProductId } from "@/api/jewelry/bracelet.js";
import { computed, ref } from "vue";

const { proxy } = getCurrentInstance();
const { product_has_stock } = proxy.useDict("product_has_stock");

const productList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const braceletCategoryId = ref(null); // 手镯分类的id
const ringCategoryId = ref(null);//戒指分类Id
const showSizeSection  = ref(false); // 是否显示尺码区域

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    name: null,
    hasStock: null,
    price: null,
    newPrice: null,
    offPercent: null,
    summary: null,
    pid: null
  },
  rules: {},
});
const categoriesSelected = ref(null)//存储用户选的分类
const categoriesOptions = ref([])//获取存储后端传来的所有分类项
const tagsSelected = ref([])//存储用户选的标签
const tagsOptions = ref([])//获取存储后端传来的所有标签项
const prodPartitionSelected = ref([])//存储用户选的分区
const prodPartitionOptions = ref([])//获取存储后端传来的所有分区项
const brandOptions = ref([])//获取从后端传来的所有品牌项
const { queryParams, form, rules } = toRefs(data);
const braceletSize = ref('')//尺码


// 转换后的原价(查询表单)
const queryParamsFormattedPrice = computed({
  get() {
    return (queryParams.value.price / 100).toFixed(2);
  },
  set(value) {
    if( !value ){
      return 
    }
    queryParams.value.newPrice = Math.round(parseFloat(value) * 100);
  },
});
// 转换后的折扣价(查询表单)
const queryParamsFormattedNewPrice = computed({
  get() {
    return (queryParams.value.newPrice / 100).toFixed(2);
  },
  set(value) {
    queryParams.value.newPrice = Math.round(parseFloat(value) * 100);
  },
});
// 显示格式化后的原价（表单）
const formattedPrice = computed({
  get() {
    return (form.value.price / 100).toFixed(2);
  },
  set(value) {
    form.value.price = Math.round(parseFloat(value) * 100);
  },
});
// 显示格式化后的折扣价（表单）
const formattedNewPrice = computed({
  get() {
    return (form.value.newPrice / 100).toFixed(2);
  },
  set(value) {
    form.value.newPrice = Math.round(parseFloat(value) * 100);
  },
});
// 监听原价变化，更新格式化后的原价
watch(
  () => queryParams.value.price,
  (newPrice) => {
    if (newPrice !== null) {
      queryParamsFormattedPrice.value = (newPrice / 100).toFixed(2);
    }
  }
);
// 监听折扣价变化，更新格式化后的折扣价
watch(
  () => queryParams.value.newPrice,
  (newNewPrice) => {
    if (newNewPrice !== null) {
      queryParamsFormattedNewPrice.value = (newNewPrice / 100).toFixed(2);
    }
  }
);
// 监听表单中原价变化，更新格式化后的原价
watch(
  () => form.value.price,
  (newFormPrice) => {
    if (newFormPrice !== null) {
      formattedPrice.value = (newFormPrice / 100).toFixed(2);
    }
  }
);
// 监听表单中折扣价变化，更新格式化后的折扣价
watch(
  () => form.value.newPrice,
  (newFormNewPrice) => {
    if (newFormNewPrice !== null) {
      formattedNewPrice.value = (newFormNewPrice / 100).toFixed(2);
    }
  }
);
// 监听分类选中的Id
const handCategoryChange = () =>{
  showSizeSection.value = 
    categoriesSelected.value === braceletCategoryId.value || categoriesSelected.value === ringCategoryId.value
}


/** 查询产品管理列表 */
function getList() {
  loading.value = true;
  listProduct(queryParams.value).then((response) => {
    productList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    atlas: '',
    mainImage:'',
    hasStock: null,
    price: null,
    newPrice: null,
    offPercent: null,
    summary: null,
    description: null,
    additionalInfo: null,
    brandId:null,
    createTime: null,
    updateTime: null,
    pid: 0,
  };
  showSizeSection.value = false
  categoriesSelected.value = null;
  tagsSelected.value = [];
  prodPartitionSelected.value = []; // 添加分区重置
  braceletSize.value = '';
  proxy.resetForm("productRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加产品管理";
  categoriesSelected.value = null;// 强制重置为未选中状态
  getCategories()
  getTags()
  getProdPartition()
  getbrands()
  categoriesSelected.value = null;// 强制尺码重置为未选中状态
  braceletSize.value = '';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getProduct(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改产品管理";
    //选过的尺码回显
    getBraceletByProductId(_id).then((res) => {
      braceletSize.value = res.data.length > 0 ? (res.data[0].size || '') : '';
    })
  });
  getCategories()
  getTags()
  getProdPartition()
  getbrands()
  //（分类，标签，分区）回显,打开显示之前选的标签
  listSelectRels(_id).then((res) => {
    categoriesSelected.value = res.data.categoryIds?.[0] || null;
    tagsSelected.value = res.data.tagIds || [];
    if(res.data.partitionIds && res.data.partitionIds.length > 0){
      prodPartitionSelected.value = res.data.partitionIds.map(id => String(id));
    } else {
      prodPartitionSelected.value = [];
    }
    //选择了手镯或戒指，就有尺码弹窗
    if(categoriesSelected.value === braceletCategoryId.value || categoriesSelected.value === ringCategoryId.value){
      showSizeSection.value = true;
    }
  });
    form.atlas = form.value.atlas || '';
    form.mainImage = form.value.mainImage || '';
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate((valid) => {
    if (valid) {
      const braceletSizeData = braceletSize.value 
        ? [{ productId: form.value.id, size: braceletSize.value }]  : [];//手镯
      const partitionIds = prodPartitionSelected.value.map(id => parseInt(id));
      if(form.value.id != null){
        const vo = {
          product:form.value,
          categoryIds:[categoriesSelected.value],
          tagIds:tagsSelected.value,
          prodPartitionIds:partitionIds,
          braceletSizes: braceletSizeData//尺码
        }
        console.log(vo)
        updateProduct(vo).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProduct({
          product:form.value,
          categoryIds: [categoriesSelected.value],
          tagIds:tagsSelected.value,
          prodPartitionIds:partitionIds,
          braceletSizes: braceletSizeData//尺码
        }).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除产品管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delProduct(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "jewelry/product/export",
    {
      ...queryParams.value,
    },
    `product_${new Date().getTime()}.xlsx`
  );
}

//查询获取后端全部分类
function getCategories () {
  listCategoryAll().then(res => {
    let categoriesLabelAndValueList = []
    for (let i = 0; i < res.data.length; i++) {
      categoriesLabelAndValueList.push({
        label: res.data[i].name,
        value: res.data[i].id
      })
      //当选择手镯出现尺码
      if (res.data[i].name === 'bracelet / 手链手镯'){
        braceletCategoryId.value = res.data[i].id;
        console.log("手镯分类ID:", braceletCategoryId.value); // 调试：确认ID已赋值
      }
      //当选择戒指出现尺码
      if (res.data[i].name === 'Ring / 戒指'){
        ringCategoryId.value =res.data[i].id;
      }
    }
    // 高级写法
    // let categoriesLabelAndValueList = res.data.map(category => {
    //   return {
    //     label: category.name,
    //     value: category.id
    //   }
    // })
    categoriesOptions.value = categoriesLabelAndValueList
  })
}

//查询获取后端全部标签
function getTags () {
  listTagAll().then(res => {
    let tagsLabelAndValueList = res.data.map(tag =>{
      return{
        label:tag.name,
        value:tag.id
      }
    })
    tagsOptions.value = tagsLabelAndValueList
  })
}

//查询获取后端全部分区
function getProdPartition (){
  listProdPartitionAll().then( res => {
    let ProdPartitionLabelAndValueList = res.data.map(ProdPartition => {
      return{
        label:ProdPartition.title,
        value:String(ProdPartition.id)
      }
    })
    prodPartitionOptions.value = ProdPartitionLabelAndValueList;
  })
}

//查询获取后端全部品牌
function getbrands (){
  listBrandAll().then((res) => {
    let brandLabelAndValueList = res.data.map(brand => {
      return{
        label:brand.name,
        value:brand.id
      }
    })
    brandOptions.value = brandLabelAndValueList
  })
}

/** 复制按钮操作 */
function handCopy(row){
  // if( row.pid !==0){
  //   proxy.$modal.msgWarning ('此产品不可以复制(仅原始产品可复制)');
  //   return;
  // }
  proxy.$modal.confirm('是否确认复制该产品').then(() => {
    copyProduct(row.id).then((res) => {
      if(res.code === 200){
        proxy.$modal.msgSuccess("复制成功");
        queryParams.value.pid = row.id
        getList();
      } else {
        proxy.$modal.msgSuccess(res.msg || "复制失败");
      }
    })
  })
}

// 上传图集成功回调
function handleAtlasUploadSuccess(res, file) {
  // 字符串拼接而非数组push
  if (form.value.atlas) {
    form.value.atlas += ',' + file.url;
  } else {
    form.value.atlas = file.url;
  }
}
getList();
</script>